package com.joysuch.wwyt.edu.service.impl;

import com.google.common.collect.Lists;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.edu.bean.*;
import com.joysuch.wwyt.edu.entity.EduCourseStatistics;
import com.joysuch.wwyt.edu.entity.EduCourseware;
import com.joysuch.wwyt.edu.mapper.EduCourtTrainningRecordMapper;
import com.joysuch.wwyt.edu.repository.*;
import com.joysuch.wwyt.edu.service.EduCourtTrainningRecordService;
import com.joysuch.wwyt.util.PoiUtil;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 描述：
 *
 * @author Eric
 * @since 2022-07-05
 */
@Service
@Slf4j
public class EduCourtTrainningRecordServiceImpl implements EduCourtTrainningRecordService {

    @Autowired
    private EduCourtTrainningRecordMapper eduCourtTrainningRecordMapper;
    @Autowired
    private EduCoursewareDao coursewareDao;

    @Override
    public ResultBean courseRecordQueryPage(EduTrainningRecordQueryBean param) {
        Pageable pageable = PageRequest.of(param.getPage(), param.getSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EduTrainningRecordQueryDto> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageable.getPageNumber() + 1, pageable.getPageSize());
        Long currentTenantId = Context.getCurrentTenantId();
        String currentOrgCode = Context.getCurrentOrgCode();
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<EduTrainningRecordQueryDto> eduCourtTrainningRecordList = eduCourtTrainningRecordMapper.getCourseRecordQueryPageList(page,
                param.getDepartName(), param.getUserName(), param.getTrainningBeginTime(),param.getTrainningStopTime(), currentTenantId, currentOrgCode);
        List<EduTrainningRecordQueryDto> records = eduCourtTrainningRecordList.getRecords();
        if (records.isEmpty()){
            return ResultBean.pageData(records, page.getTotal());
        }
        for (EduTrainningRecordQueryDto eduTrainningRecordQueryDto: records) {
            eduTrainningRecordQueryDto.setLeaningTime(calLearnTime(Long.valueOf(eduTrainningRecordQueryDto.getLeaningTime())));
        }
        return ResultBean.pageData(records, page.getTotal());
    }

    @Override
    public void courtRecordExcel(EduTrainningRecordQueryBean param, HttpServletRequest request, HttpServletResponse response) {
        Assert.notNull(param, "param cannot be null");
        List<EduTrainningRecordQueryDto> eduTrainningRecordQueryDtoList = eduCourtTrainningRecordMapper.getCourseRecordQueryList(param.getDepartName(),param.getUserName(), param.getTrainningBeginTime(),param.getTrainningStopTime(),Context.getCurrentTenantId(), Context.getCurrentOrgCode());
        String file = "学习记录.xls";
        response.setContentType(request.getServletContext().getMimeType(file));
        HSSFWorkbook hwb = null;
        try {
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + file + "\"; filename*=utf-8' ' " + URLEncoder.encode(file, "utf-8"));
            List<String> cellNames = getCellName();
            Pair<HSSFWorkbook, HSSFSheet> pair = PoiUtil.getPoi("学习记录", cellNames);
            for (EduTrainningRecordQueryDto eduTrainningRecordQueryDto: eduTrainningRecordQueryDtoList) {
                eduTrainningRecordQueryDto.setLeaningTime(calLearnTime(Long.valueOf(eduTrainningRecordQueryDto.getLeaningTime())));
                EduTrainningRecordQueryDto userLeaningTotleTime = eduCourtTrainningRecordMapper.getUserLeaningTotleTime(param.getDepartName(), eduTrainningRecordQueryDto.getLeaningTotalTime(), param.getTrainningBeginTime(), param.getTrainningStopTime(), Context.getCurrentTenantId(), Context.getCurrentOrgCode());
                String time=eduTrainningRecordQueryDto.getLeaningTime();
                if (userLeaningTotleTime!=null) {
                    time   = calLearnTime(Long.valueOf(userLeaningTotleTime.getLeaningTotalTime()));
                }
                eduTrainningRecordQueryDto.setLeaningTotalTime(time);
            }
            addRecordData(eduTrainningRecordQueryDtoList, pair);
            hwb = pair.getKey();
            hwb.write(response.getOutputStream());
        } catch (IOException e) {
            log.warn("线上教育excel导出失败：" + e.getMessage());
            throw new IllegalArgumentException("excel导出失败，请联系系统管理员");
        } finally {
            if (hwb != null) {
                try {
                    hwb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 计算学习时长 xxx s -> 128h30m23s
     */
    private String calLearnTime(Long courseLearnTime) {
        if (courseLearnTime == 0) {
            return courseLearnTime + "s";
        }
        long minute = courseLearnTime / 60;
        long second = courseLearnTime % 60;
        if (minute == 0) {
            return second + "s";
        }
        if (minute < 60) {
            return minute + "m" + second + "s";
        } else {
            long hour = minute / 60;
            long tempMinute = minute % 60;
            return hour + "h" + tempMinute + "m" + second + "s";
        }
    }
    private void addRecordData(List<EduTrainningRecordQueryDto> trainningRecordQueryList, Pair<HSSFWorkbook, HSSFSheet> pair) {
        HSSFSheet sheet = pair.getValue();
        int index = 1;
        for (int i = 0; i < trainningRecordQueryList.size(); i++) {
            EduTrainningRecordQueryDto dto = trainningRecordQueryList.get(i);
            HSSFRow row = sheet.createRow(i + 1);
            row = sheet.createRow(i + 1);
//            row.createCell(0).setCellValue(index++);
            row.createCell(0).setCellValue(dto.getLearningContent());
            row.createCell(1).setCellValue(dto.getUpdateTime());
            row.createCell(2).setCellValue(dto.getDepartName());
            row.createCell(3).setCellValue(dto.getUserName());
            row.createCell(4).setCellValue(dto.getLeaningTime());
            row.createCell(5).setCellValue(dto.getLeaningTotalTime());
            row.createCell(6).setCellValue(dto.getState()==0?"否":"是");
        }
    }

    private List<String> getCellName() {
        List<String> list = Lists.newArrayList();
//        list.add("序号");
        list.add("学习内容");
        list.add("日期");
        list.add("所属部门");
        list.add("人员");
        list.add("学习时长");
        list.add("总时长");
        list.add("是否视频复习");
        return list;
    }

}
